package model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TagModel {

  Connection connection;

  public TagModel(Connection connection) {
    this.connection = connection;
  }

  public void insertTag(String type) {
    try {
      String query = "INSERT INTO tag (type) VALUES ('" + type + "')";
      Statement statement = connection.createStatement();
      statement.executeUpdate(query);
    } catch (Exception ex) {
      //kalo udah ada, ntar jadinya error integrity, tapi biarin aja
    }
  }

  public ResultSet getTagInfoByType(String type) throws SQLException {
    String query = "SELECT * FROM tag WHERE type='$type' LIMIT 1";
    Statement statement = connection.createStatement();
    ResultSet rs = statement.executeQuery(query);
    return rs;
  }

  public void insertPostTag(int postId, int tagId) throws SQLException {
    String query = "INSERT INTO post_tag (post_id, tag_id) VALUES ('" + postId + "', '" + tagId + "')";
    Statement statement = connection.createStatement();
    statement.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);
  }

  public ResultSet getTagInfo(int post_id) throws SQLException {
    String query = "SELECT * "
            + "FROM post_tag "
            + "INNER JOIN tag "
            + "ON tag_id=tag.ID "
            + "WHERE post_id = " + post_id;
    Statement statement = connection.createStatement();
    return statement.executeQuery(query);
  }

  public ResultSet getTags(String post_id) throws SQLException {
    String query = "SELECT type FROM post INNER JOIN post_tag ON post_tag.post_id=post.ID INNER JOIN tag ON tag.ID=post_tag.tag_id INNER JOIN user ON user.ID=post.poster_id WHERE post_tag.post_id = "+post_id;
    System.out.println(query);
    Statement statement = connection.createStatement();
    return statement.executeQuery(query);
  }
  
}
